package com.yuncheng.spcyApi.spcyService;

import cn.hutool.core.collection.CollectionUtil;
import com.yuncheng.entity.YcSysUser;
import com.yuncheng.vo.CurrentUserVo;
import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.yuncheng.spcyApi.constant.common.ClientJumpUrlConstant;
import com.yuncheng.spcyApi.constant.common.SpcyCommonConstant;
import com.yuncheng.spcyApi.constant.common.SpcyConstant;
import com.yuncheng.spcyApi.constant.jcy.JcydjbConstant;
import com.yuncheng.spcyApi.entity.*;
import com.yuncheng.spcyApi.flow.SpcyFlowConstant;
import com.yuncheng.spcyApi.mapper.SpcyFlowMapper;
import com.yuncheng.spcyApi.mapper.YcSysUserMapper;
import com.yuncheng.spcyApi.service.*;
import com.yuncheng.spcyApi.utils.GetCurrentUserUtils;
import com.yuncheng.spcyApi.utils.StringPatternUtils;

import com.yuncheng.spcyApi.vo.common.PageVo;
import com.yuncheng.spcyApi.vo.common.WeekMapVo;
import com.yuncheng.spcyApi.vo.jcy.JcyJcrcVo;
import com.yuncheng.spcyApi.vo.spcy.SpcyJobVo;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Component;
import utils.DateConversionUtils;

import javax.annotation.Resource;
import java.time.LocalDate;
import java.time.YearMonth;
import java.time.ZoneId;
import java.time.temporal.ChronoField;
import java.time.temporal.TemporalAdjusters;
import java.time.temporal.WeekFields;
import java.util.*;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.Executor;
import java.util.concurrent.atomic.AtomicLong;
import java.util.stream.Collectors;

/**
 * 个人信息
 */
@Component(value = "spcyMyInfoService")
public class SpcyMyInfoService {

    private static final Logger log = LoggerFactory.getLogger(SpcyMyInfoService.class);

    @Resource
    @Lazy
    private IYcSysUserService ycSysUserService;

    @Resource
    private YcSysUserMapper ycSysUserMapper;

    @Resource
    @Lazy
    private SpcyFlowMapper spcyFlowMapper;

    @Resource
    @Lazy
    private ISpcyRsHcyService spcyRsHcyService;

    @Resource
    private ISysConfigService sysConfigService;

    @Resource
    @Lazy
    private ISpcySqsxWjjlService spcySqsxWjjlService;

    @Resource
    private ClientJumpUrlConstant clientJumpUrlConstant;

    @Autowired
    @Qualifier("asyncNormalTask")
    private Executor executor;

    /**
     * 我的基本信息
     * @param userid
     * @return
     */
    public Map queryMyJbxx(String userid){
        Map map = new HashMap();

        YcSysUser user = ycSysUserService.getById(userid);
        map.put("user",user);

        /******************************** 【      检 查 员    】  *********************************************************** */
        List<Map> resultMap = new ArrayList<>();

        // 所有相关有效检查员
//        List<SpcyRsHcy> hcyList = spcyRsHcyService.selectJcyListByUserId(userid);
        List<SpcyRsHcy> hcyList = spcyRsHcyService.selectJcyYxList(userid);

        if (CollectionUtil.isNotEmpty(hcyList)) {
            String lbs = this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_LBS_CODE);
            List<String> lbList = StringPatternUtils.getListByIds(lbs);
            for (String lb : lbList) {
                for (int i = 0; i < hcyList.size(); i++) {
                    if (hcyList.get(i).getFlx().equals(lb)) {
                        Map hcyMap = new HashMap();
                        hcyMap.put("jcy", hcyList.get(i));
                        hcyMap.put("typeList", this.getJctcWithLb(lb));
                        resultMap.add(hcyMap);
                    }
                }
            }
        }
        map.put("jcyList", resultMap);

        return map;
    }

    /** 获取app我的信息 */
    public Map selectAppMyInfo(String userid){
        Map resultMap = new HashMap();

        resultMap.put("user", ycSysUserMapper.findAppUserJbxxById(userid));
        resultMap.put("photoLink", genUserPhotoLink(userid));
        return resultMap;
    }

    /**
     * 查询用户所有的检查员身份
     * @param userid
     * @return
     */
    public Map getUserJcysfList(String userid){
        // 所有相关有效检查员
//        List<SpcyRsHcy> hcyList = spcyRsHcyService.selectJcyListByUserId(userid);
        List<SpcyRsHcy> hcyList = spcyRsHcyService.selectJcyYxList(userid);

        Map resultMap = new HashMap();
        List<Map> resultMapList = new ArrayList<>();
        if (CollectionUtil.isNotEmpty(hcyList)){

            List<SpcyRsHcy> ypList = new ArrayList<>();
            List<SpcyRsHcy> ylqxList = new ArrayList<>();
            List<SpcyRsHcy> hzpList = new ArrayList<>();

            String ybsskLx = "";
            String zysskLx = "";
            String zzsskLx = "";

            for (SpcyRsHcy jcy : hcyList){

                if (StringUtils.isNotBlank(jcy.getFxllx())){
                    if (jcy.getFxllx().equals(SpcyConstant.XLLX_YP)){
                        ypList.add(jcy);
                    }else if (jcy.getFxllx().equals(SpcyConstant.XLLX_YLQX)){
                        ylqxList.add(jcy);
                    }else if (jcy.getFxllx().equals(SpcyConstant.XLLX_HZP)){
                        hzpList.add(jcy);
                    }
                }

                if (StringUtils.isNotBlank(jcy.getFssk())){
                    if (jcy.getFssk().equals(SpcyConstant.HCY_SSK_YB)){

                        if (StringUtils.isNotBlank(jcy.getFjcyxl())) {
                            if (StringUtils.isNotBlank(ybsskLx)){
                                ybsskLx += "、";
                            }
                            ybsskLx += jcy.getFjcyxl();
                        }
                    }else if (jcy.getFssk().equals(SpcyConstant.HCY_SSK_ZY)){

                        if (StringUtils.isNotBlank(jcy.getFjcyxl())) {
                            if (StringUtils.isNotBlank(zysskLx)){
                                zysskLx += "、";
                            }

                            zysskLx += jcy.getFjcyxl();
                        }
                    }else if (jcy.getFssk().equals(SpcyConstant.HCY_SSK_ZZ)){
                        if (StringUtils.isNotBlank(jcy.getFjcyxl())) {
                            if (StringUtils.isNotBlank(zzsskLx)){
                                zzsskLx += "、";
                            }
                            zzsskLx += jcy.getFjcyxl();
                        }
                    }
                }

            }

            if (StringUtils.isNotBlank(ybsskLx)){
                ybsskLx ="（"+ ybsskLx +"）";
            }
            if (StringUtils.isNotBlank(zysskLx)){
                zysskLx ="（"+ zysskLx +"）";
            }
            if (StringUtils.isNotBlank(zzsskLx)){
                zzsskLx ="（"+ zzsskLx +"）";
            }

            /*List<SpcyRsHcy> ypList = hcyList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFxllx())
                            && f.getFxllx().equals(SpcyConstant.XLLX_YP))
                    .collect(Collectors.toList());*/


            Map ypdataMap = new HashMap();
            ypdataMap.put("xllx", SpcyConstant.XLLX_YP);
            ypdataMap.put("ssk", SpcyConstant.HCY_SSK_YB);
            ypdataMap.put("sskLx", ybsskLx);
            ypdataMap.put("list", ypList);
            resultMapList.add(ypdataMap);

            /*List<SpcyRsHcy> ylqxList = hcyList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFxllx())
                            && f.getFxllx().equals(SpcyConstant.XLLX_YLQX))
                    .collect(Collectors.toList());*/

            Map ylqxdataMap = new HashMap();
            ylqxdataMap.put("xllx", SpcyConstant.XLLX_YLQX);
            ylqxdataMap.put("ssk", SpcyConstant.HCY_SSK_ZY);
            ylqxdataMap.put("sskLx", zysskLx);
            ylqxdataMap.put("list", ylqxList);
            resultMapList.add(ylqxdataMap);

            /*List<SpcyRsHcy> hzpList = hcyList.stream()
                    .filter(f -> StringUtils.isNotBlank(f.getFxllx())
                            && f.getFxllx().equals(SpcyConstant.XLLX_HZP))
                    .collect(Collectors.toList());*/


            Map hzpdataMap = new HashMap();
            hzpdataMap.put("xllx", SpcyConstant.XLLX_HZP);
            hzpdataMap.put("ssk", SpcyConstant.HCY_SSK_ZZ);
            hzpdataMap.put("sskLx", zzsskLx);
            hzpdataMap.put("list", hzpList);
            resultMapList.add(hzpdataMap);
        }

        YcSysUser user = ycSysUserService.getById(userid);
        resultMap.put("user", user);
        resultMap.put("lbList", resultMapList);
        return resultMap;
    }

    /**
     * 系统参数查询
     * @param code
     * @return
     */
    public String getSysConfigByCode(String code){
        String msg = null;

        List<SysConfig> config = sysConfigService.list(new LambdaQueryWrapper<SysConfig>()
                .eq(SysConfig::getConfigCode, code));

        if (CollectionUtils.isNotEmpty(config)){
            msg = config.get(0).getConfigValue();
        }

        return msg;
    }

    /**
     * 检查员-不同序列类型-对应的特长
     * @param lb
     * @return
     */
    public String getJctcWithLb(String lb){

        if (lb.equals(JcydjbConstant.LB_YPLC)){
            return Optional.ofNullable(this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_JCYTC_YWLC_JCTC)).orElseGet(() -> "");
        }
        else if (lb.equals(JcydjbConstant.LB_YPZCSC)){
            return Optional.ofNullable(this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_JCYTC_YPZCSC_JCTC)).orElseGet(() -> "");
        }
        else if (lb.equals(JcydjbConstant.LB_YPLT)){
            return Optional.ofNullable(this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_JCYTC_YPLT_JCTC)).orElseGet(() -> "");
        }
        else if (lb.equals(JcydjbConstant.LB_YLQXSCLT)){
            return Optional.ofNullable(this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_JCYTC_YLQXSCLT_JCTC)).orElseGet(() -> "");
        }
        else if (lb.equals(JcydjbConstant.LB_YLQXLC)){
            return Optional.ofNullable(this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_JCYTC_YLQXLC_JCTC)).orElseGet(() -> "");
        }
        else if (lb.equals(JcydjbConstant.LB_HZPJCY)){
            return Optional.ofNullable(this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_JCYTC_HZPJCY_JCTC)).orElseGet(() -> "");
        }

        return Optional.ofNullable(this.getSysConfigByCode(JcydjbConstant.SYS_CONFIG_JCYTC_YPZCSC_JCTC)).orElseGet(() -> "");
    }

    /**
     * 生成用户签名/照片链接
     * @param userid 用户id
     * @return {
     *     signLink: 签名链接
     *     photoLink: 照片链接
     *     jcyZjLink: 检查员证件链接
     * }
     */
    public Map getUserSignPhotoLink(String userid){
        return getUserSignPhotoLink(userid, false);
    }

    public Map getUserSignPhotoLink(String userid, boolean isWhiteList){
        Map resultMap = new HashMap();

        resultMap.put("signLink", genUserSignLink(userid));
        resultMap.put("photoLink", genUserPhotoLink(userid));

        if (!isWhiteList) {
            resultMap.put("jcyZjLink", genUserJcyZjLink(userid));
        }

        return resultMap;
    }

    /**
     * 获取多用户签名列表
     * @param ids 用户ids
     * @return
     */
    public List<Map> getMoreUserSignLinkList(String ids){
        List<Map> resultMap = new ArrayList<>();

        if (StringUtils.isBlank(ids)){
            return resultMap;
        }
        String[] idsStrings = StringPatternUtils.getStringsByIds(ids);
        for (int i = 0; i < idsStrings.length; i++){
            Map dataMap = new HashMap();
            dataMap.put("userid", idsStrings[i]);
            dataMap.put("signLink", genUserSignLink(idsStrings[i]));
            dataMap.put("name", Optional.ofNullable(ycSysUserService.getUserJbxxById(idsStrings[i])).map(f -> f.getRealname()).orElseGet(()->""));
            resultMap.add(dataMap);
        }

        return resultMap;
    }

    /**
     * 生成用户签名链接
     * @param userid 用户id
     */
    public String genUserSignLink(String userid){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        SpcySqsxWjjl signWjjl = spcySqsxWjjlService.downMyUserQm(userid, currentUser);
        if (signWjjl != null) {
            return clientJumpUrlConstant.zdyfjDownloadHttpsUrl + signWjjl.getId();
        }
        return "";
    }

    /**
     * 生成用户照片链接
     * @param userid 用户id
     */
    public String genUserPhotoLink(String userid){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        SpcySqsxWjjl photoWjjl = spcySqsxWjjlService.downMyUserPhoto(userid, currentUser);
        if (photoWjjl != null) {
            return clientJumpUrlConstant.zdyfjDownloadHttpsUrl + photoWjjl.getId();
        }
        return "";
    }

    /**
     * 生成用户检查员证件链接
     * @param userid 用户id
     */
    private String genUserJcyZjLink(String userid){
        CurrentUserVo currentUser = GetCurrentUserUtils.getCurrentUser();
        SpcySqsxWjjl photoWjjl = spcySqsxWjjlService.downMyUserJcyZj(userid, currentUser);
        if (photoWjjl != null) {
            return clientJumpUrlConstant.zdyfjDownloadHttpsUrl + photoWjjl.getId();
        }
        return "";
    }

    /**
     * 检查日程
     * @param userid 用户id
     * @param nowDate 当前日期
     */
    public Map getJcrc(String userid, String nowDate) {

        // 检查日程
        List<JcyJcrcVo> jcrcList = spcyFlowMapper.selectJcyJcrcList(userid, SpcyConstant.XPJL_SFTYXP_YES);

        if (StringUtils.isNotBlank(nowDate) && CollectionUtil.isNotEmpty(jcrcList)){
            jcrcList = jcrcList.stream()
                    .filter(f -> f.getFcyjssj()!=null && f.getFcyjssj().equals(DateConversionUtils.convertStringToDateYmd(nowDate)))
                    .collect(Collectors.toList());
        }
        List<Map> resultMapList = new ArrayList<>(jcrcList.size()+1);
        if (CollectionUtil.isNotEmpty(jcrcList)){
            for (JcyJcrcVo jcrc : jcrcList){
                List<String> dateList = DateConversionUtils.getTwoDateMidDateList(jcrc.getFcykssj(), jcrc.getFcyjssj());

                Map dataMap = new HashMap();
                dataMap.put("jbxx", jcrc);
                dataMap.put("dateList", dateList);
                resultMapList.add(dataMap);
            }
        }else {
            Map dataMap = new HashMap();
            JcyJcrcVo jcrc = new JcyJcrcVo();
            jcrc.setFcykssj(DateConversionUtils.convertStringToDateYmd("2024-01-06"));
            jcrc.setFcyjssj(DateConversionUtils.convertStringToDateYmd("2024-01-30"));
            jcrc.setFqymc("广西南宁百会药业集团有限公司");
            jcrc.setFqyzszcdz("广西南宁市金阳路39号");
            jcrc.setFssk("组员");
            jcrc.setFsxmc("药品生产质量管理规范符合性检查申请");
            dataMap.put("jbxx", jcrc);

            List<String> dateList = DateConversionUtils.getTwoDateMidDateList(jcrc.getFcykssj(), jcrc.getFcyjssj());
            dataMap.put("dateList", CollectionUtil.newArrayList(dateList));
            resultMapList.add(dataMap);
        }

        Map resultMap = new HashMap();
        resultMap.put("jcrcList", resultMapList);
        return resultMap;
    }

    /**
     * 检查员个人相关-流程待办数量
     */
    public Map getXcjcKpDbsl(String userid, PageVo pageVo){

        Map resultMap = new HashMap();

        Page<SpcySqsxJob> page = new Page<>(pageVo.getPageNo(), pageVo.getPageSize());

        /** 验证是否为检查员身份 */
        if (GetCurrentUserUtils.getCurrentUserOrgId().equals(SpcyConstant.HCY_ORGID)){
            // 查验
            resultMap.put("spcyCount",
                    spcyFlowMapper.selectCommonFlowList(page, userid, SpcyFlowConstant.HJMC_XCJC, SpcyFlowConstant.LCMC_LIKE_SPCYLC, SpcyConstant.BLZT_DB)
                            .getTotal());

            Page<SpcySqsxJob> kpPageList = spcyFlowMapper.selectCommonFlowList(new Page<>(1, 100), userid, null, null, SpcyConstant.BLZT_DB);

            // 查验
            /*int spcySize = kpPageList.getRecords()
                    .stream()
                    .filter(f-> f.getFlcmc().contains(SpcyFlowConstant.LCMC_LIKE_SPCYLC))
                    .collect(Collectors.toList())
                    .size();

            resultMap.put("spcyCount", spcySize);*/

            // 见习
            int jxkpSize = kpPageList.getRecords()
                    .stream()
                    .filter(f-> f.getFlcmc().contains(SpcyFlowConstant.YBKP_LCMC))
                    .collect(Collectors.toList())
                    .size();

            // 日常互评
            int rchpSize = kpPageList.getRecords()
                    .stream()
                    .filter(f-> f.getFlcmc().contains(SpcyFlowConstant.RCKPHP_LCMC))
                    .collect(Collectors.toList())
                    .size();

            // 见习
            /*long jxkpSize = spcyFlowMapper.selectCommonFlowList(page, userid, null, SpcyFlowConstant.YBKP_LCMC, SpcyConstant.BLZT_DB)
                                    .getTotal();*/

            // 日常互评
            /*long rchpSize = spcyFlowMapper.selectCommonFlowList(page, userid, null, SpcyFlowConstant.RCKPHP_LCMC, SpcyConstant.BLZT_DB)
                                        .getTotal();*/

            resultMap.put("jcgzkhCount", jxkpSize + rchpSize);

        }else {
            // 查验
            resultMap.put("spcyCount",
                    spcyFlowMapper.selectCommonFlowList(page, userid, null, SpcyFlowConstant.LCMC_LIKE_SPCYLC, SpcyConstant.BLZT_DB)
                            .getTotal());
        }

//        Page<SpcySqsxJob> ndkpList = spcyFlowMapper.selectCommonFlowList(page, userid, SpcyFlowConstant.NDKP_LCMC, SpcyConstant.BLZT_DB);
//        Page<SpcySqsxJob> rckpList = spcyFlowMapper.selectCommonFlowList(page, userid, SpcyFlowConstant.RCKP_LCMC2, SpcyConstant.BLZT_DB);

        /*resultMap.put("rckpCount", spcyFlowMapper.selectCommonFlowList(page, userid, null, SpcyFlowConstant.RCKP_LCMC, SpcyConstant.BLZT_DB)
                .getTotal());*/

        /*resultMap.put("ndkpCount", spcyFlowMapper.selectCommonFlowList(page, userid, null, SpcyFlowConstant.NDKP_LCMC, SpcyConstant.BLZT_DB)
                .getTotal());*/

        return resultMap;
    }

    /**
     * 获取个人待办考评待办
     */
    public int getMyKpDbsl(String userid){
        Page<SpcySqsxJob> kpPageList = spcyFlowMapper.selectCommonFlowList(new Page<>(1, 100), userid, null, null, SpcyConstant.BLZT_DB);
        // 见习
        int jxkpSize = kpPageList.getRecords()
                .stream()
                .filter(f-> f.getFlcmc().contains(SpcyFlowConstant.YBKP_LCMC))
                .collect(Collectors.toList())
                .size();

        // 日常互评
        int rchpSize = kpPageList.getRecords()
                .stream()
                .filter(f-> f.getFlcmc().contains(SpcyFlowConstant.RCKPHP_LCMC))
                .collect(Collectors.toList())
                .size();

        return jxkpSize + rchpSize;
    }


    /**
     * 获取检查员考评相关待办数据
     */
    public Map kpdbListByUserIdAndSqsxId(String sqsxid, String userid){
        if (StringUtils.isBlank(userid)){
            userid = GetCurrentUserUtils.getCurrentUserId();
        }
        Map resultMap = new HashMap();

        // 见习考评
        resultMap.put("jxkpJobList", spcyFlowMapper.selectJxkpDbByFsqsxidAndFuserid(sqsxid, userid));

        // 日常考评
        resultMap.put("rckpJobList", spcyFlowMapper.selectRckpDbByFsqsxidAndFuserid(sqsxid, userid, SpcyFlowConstant.RCKP_LCMC));

        return resultMap;
    }

    /**
     * 检查员学历/职称分布情况
     */
    public Map jcyxlzcfbqk(){
        Map resultMap = new HashMap();

        List<String> xlTypeList = CollectionUtil.newArrayList("专科","本科","硕士研究生","博士研究生","其他");
        List<String> zcTypeList = CollectionUtil.newArrayList("初级","中级","副高","正高","其他","无");

        List<Map> xlDataMapList = new ArrayList<>();
        List<Map> zcDataMapList = new ArrayList<>();

        List<YcSysUser> jcyUserList = spcyRsHcyService.selectJcyUserJbxxList(new YcSysUser());

        // 学历
        for (String xl : xlTypeList) {
            Map xlMap = new HashMap();

            int size = 0;
            if (CollectionUtil.isNotEmpty(jcyUserList)){
                if (!xl.equals("其他")) {
                    size = jcyUserList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFxl()) && f.getFxl().equals(xl))
                            .collect(Collectors.toList()).size();
                } else {
                    size = jcyUserList.stream()
                            .filter(f -> StringUtils.isBlank(f.getFxl()) || !xlTypeList.contains(f.getFxl()) || f.getFxl().equals(xl)
                            )
                            .collect(Collectors.toList()).size();
                }
            }

            xlMap.put("type", xl);
            xlMap.put("size", size);
            xlDataMapList.add(xlMap);
        }

        // 职称
        for (String zc : zcTypeList) {
            Map zcMap = new HashMap();

            int size = 0;
            if (CollectionUtil.isNotEmpty(jcyUserList)) {
                if (zc.equals("其他")) {
                   /* size = jcyUserList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFzc()) && (!zcTypeList.contains(f.getFzc())) || f.getFzc().equals(zc))
                            .collect(Collectors.toList()).size();*/

                    size = jcyUserList.stream()
                            .filter(f -> (StringUtils.isNotBlank(f.getFzc()) && !zcTypeList.contains(f.getFzc()))
                                    || (StringUtils.isNotBlank(f.getFzc()) && f.getFzc().equals(zc)))
                            .collect(Collectors.toList()).size();
                } else if (zc.equals("无")) {
                    size = jcyUserList.stream()
                            .filter(f -> StringUtils.isBlank(f.getFzc()) || f.getFzc().equals(zc))
                            .collect(Collectors.toList()).size();
                } else {
                    size = jcyUserList.stream()
                            .filter(f -> StringUtils.isNotBlank(f.getFzc()) && f.getFzc().equals(zc))
                            .collect(Collectors.toList()).size();
                }
            }
            zcMap.put("type", zc);
            zcMap.put("size", size);
            zcDataMapList.add(zcMap);
        }


        resultMap.put("xlList", xlDataMapList);
        resultMap.put("zcList", zcDataMapList);
        return resultMap;
    }

    /**
     * 检查员类别分布情况
     */
    public Map jcylbfbqk(){
        Map resultMap = new HashMap();

        List<Map> resultMapList = new ArrayList<>();
        List<String> jcylbList = StringPatternUtils.getListByIds(JcydjbConstant.DJB_JCY_LBS);

        for (String lb : jcylbList) {
            int ybjcySize = 0;
            int zySize = 0;
            int zzSize = 0;

            /*List<SpcyRsHcy> list = spcyRsHcyService.list(new LambdaQueryWrapper<SpcyRsHcy>()
                    .eq(SpcyRsHcy::getFstate, SpcyCommonConstant.JCY_STATE_YX)
                    .eq(SpcyRsHcy::getFlx, lb));*/
            List<SpcyRsHcy> list = spcyRsHcyService.selectJcyJbxxList(new SpcyRsHcy(SpcyCommonConstant.JCY_STATE_YX, lb));

            if (CollectionUtil.isNotEmpty(list)){
                ybjcySize = list.stream()
                        .filter(f -> StringUtils.isNotBlank(f.getFssk()) && f.getFssk().equals(SpcyConstant.HCY_SSK_YB))
                        .collect(Collectors.toList()).size();

                zySize = list.stream()
                        .filter(f -> StringUtils.isNotBlank(f.getFssk()) && f.getFssk().equals(SpcyConstant.HCY_SSK_ZY))
                        .collect(Collectors.toList()).size();

                zzSize = list.stream()
                        .filter(f -> StringUtils.isNotBlank(f.getFssk()) && f.getFssk().equals(SpcyConstant.HCY_SSK_ZZ))
                        .collect(Collectors.toList()).size();
            }

            Map dataMap = new HashMap();

            /*String jcylb = JcydjbConstant.getJcylbByJcyxl(lb);
            if (!jcylb.equals(lb)){
                lb = jcylb + "("+lb+")";
            }*/

            dataMap.put("lb", lb);
            dataMap.put("ybjcySize", ybjcySize);
            dataMap.put("zySize", zySize);
            dataMap.put("zzSize", zzSize);

            resultMapList.add(dataMap);
        }

        resultMap.put("list", resultMapList);
        return resultMap;
    }

    /**
     * 验证登录用户-是否为科室负责人
     * @return 0：普通；1：科室负责人；2：分管领导
     */
    public String getUserKsfzrData(String userid){
        // 1为科室负责人, 2为分管领导，0: 普通
        if (StringUtils.isNotBlank(ycSysUserService.verifyUserIsZdgwry(userid, SpcyConstant.GW_NAME_KZ))){
            return "1";
        }else {
            return "0";
        }
    }

    /**
     * 验证登录用户-银行卡/电子签名/头像是否存在
     */
    public Map verifyByYkhQzdmTx(){
        Map resultMap = new HashMap();

        String userid = GetCurrentUserUtils.getCurrentUserId();
        YcSysUser userYhkInfo = ycSysUserService.getUserYhkInfo(userid);

        String yhkFlag = "0"; //1: 银行卡号为空
        String fkfhFlag = "0"; //1: 开发行为空
        String fkhhszdFlag = "0"; //1: 开户行所在地为空

        String phoneFlag = "0";// 1: 电话为空
        String emailFlag = "0";// 1: 邮箱为空
        String userSignFlag = "0"; // 1：签名为空
        String userPhotoFlag = "0"; // 1: 证件照为空

        String signLink = ""; // 签名链接
        String photoLink = ""; // 照片链接

        if (userYhkInfo != null) {

            if (StringUtils.isBlank(userYhkInfo.getFyhkh())) {
                yhkFlag = "1";
            }

            if (StringUtils.isBlank(userYhkInfo.getFkfh())) {
                fkfhFlag = "1";
            }

            if (StringUtils.isBlank(userYhkInfo.getFkhhszd())) {
                fkhhszdFlag = "1";
            }

            if (StringUtils.isBlank(userYhkInfo.getPhone())) {
                phoneFlag = "1";
            }
            if (StringUtils.isBlank(userYhkInfo.getEmail())) {
                emailFlag = "1";
            }

            signLink = this.genUserSignLink(userid); // 获取签名
            photoLink = this.genUserPhotoLink(userid); // 获取照片
            if (StringUtils.isBlank(signLink)) {
                userSignFlag = "1";
            }
            if (StringUtils.isBlank(photoLink)) {
                userPhotoFlag = "1";
            }
        }

        resultMap.put("yhkFlag", yhkFlag);
        resultMap.put("fkfhFlag", fkfhFlag);
        resultMap.put("fkhhszdFlag", fkhhszdFlag);

        resultMap.put("phoneFlag", phoneFlag);
        resultMap.put("emailFlag", emailFlag);

        resultMap.put("userSignFlag", userSignFlag);
        resultMap.put("userPhotoFlag", userPhotoFlag);

        resultMap.put("signLink", signLink);
        resultMap.put("photoLink", photoLink);

        resultMap.put("id", userid);
        return resultMap;
    }

    /**
     * 获取本月本科室-人员任务量
     */
    public List<Map> getNowUserKsryRwlInStat(String orgId, String kssj, String jssj){
        List<Map> resultList = new ArrayList<>();

        List<YcSysUser> userList = ycSysUserService.getDeptIndexUserList(orgId);

        List<SpcyJobVo> jobList = new ArrayList<>();
        String yearMonth = null;
        if (StringUtils.isNotBlank(kssj) && StringUtils.isNotBlank(jssj)){
            if (kssj.equals(jssj)){
                jobList = spcyFlowMapper.selectMySpcyRwlList(null, SpcyFlowConstant.LCMC_LIKE_SPCYLC, null, null, null,null, kssj);
            }else {
                jobList = spcyFlowMapper.selectSpcyRwlList(SpcyFlowConstant.LCMC_LIKE_SPCYLC, kssj, jssj);
            }
        }else {
            if (StringUtils.isNotBlank(kssj)){
                yearMonth = kssj;
            }else if (StringUtils.isNotBlank(jssj)){
                yearMonth = jssj;
            }else {
                yearMonth = DateConversionUtils.DateToMonth(new Date());
            }

            jobList = spcyFlowMapper.selectMySpcyRwlList(null, SpcyFlowConstant.LCMC_LIKE_SPCYLC, null, null, null,null, yearMonth);
        }

        for (int i = 0; i < userList.size(); i++) {
            String userid = userList.get(i).getId();
            long dbsl = jobList.stream()
                    .filter(f -> !f.getFblzt().equals(SpcyConstant.BLZT_YB) && f.getFdbrid().contains(userid))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            long ybsl = jobList.stream()
                    .filter(f -> f.getFblzt().equals(SpcyConstant.BLZT_YB)
                            && StringUtils.isNotBlank(f.getFblrid())
                            && f.getFblrid().equals(userid)
                    )
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            long zsl = dbsl + ybsl;
            /*long zsl = jobList.stream()
                    .filter(job -> job.getFdbrid().contains(userid))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();*/

            Map dataMap = new HashMap();
            dataMap.put("index", userList.get(i).getRealname());

            Map resultMap = new HashMap();
            resultMap.put("dbsl", dbsl);
            resultMap.put("ybsl", ybsl);
            resultMap.put("zsl", zsl);

            dataMap.put("data", resultMap);
            resultList.add(dataMap);
        }

        return resultList;
    }

    /**
     * 获取本年本科室-各环节任务量
     */
    public Map getNowUserKsHjmcRwlInStat(){
        Map resutlMap = new HashMap();

        String year = null;
        String fywflcode = SpcyConstant.getYwflByDeptName(GetCurrentUserUtils.getCurrentUserOrgName());
        List<SpcyJobVo> jobList = spcyFlowMapper.selectMySpcyRwlList(null, SpcyFlowConstant.LCMC_LIKE_SPCYLC, null,null,fywflcode, year, null);
        List<SpcyJobVo> cqjobList = spcyFlowMapper.selectMySpcyRwlList(null, SpcyFlowConstant.LCMC_LIKE_SPCYLC, SpcyConstant.BLZT_DB,"是",fywflcode, year, null);

        // 超期办件数
        int cqbjs = cqjobList.stream()
                .collect(
                Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(
                                        Comparator.comparing(o -> o.getFpid())
                                )
                        ), ArrayList<SpcyJobVo>::new
                )
        ).size();
        resutlMap.put("cqbjs", cqbjs);

        CompletableFuture<String> future1 = CompletableFuture.supplyAsync(() -> {

            // 未接收任务数量
            int wjsrwsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(SpcyFlowConstant.HJMC_RWSL) && !f.getFblzt().equals(SpcyConstant.BLZT_YB))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            // 材料审查数量
            long clscsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(SpcyFlowConstant.HJMC_CLSC) && !f.getFblzt().equals(SpcyConstant.BLZT_YB))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            resutlMap.put("wjsrwsl", wjsrwsl);
            resutlMap.put("clscsl", clscsl);

            return "1";
        }, executor);

        CompletableFuture<String> future2 = CompletableFuture.supplyAsync(() -> {

            // 方案制作数量
            long fazzsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(SpcyFlowConstant.HJMC_FAZZ) && !f.getFblzt().equals(SpcyConstant.BLZT_YB))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            // 现场检查数量
            long xcjcsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(SpcyFlowConstant.HJMC_XCJC) && !f.getFblzt().equals(SpcyConstant.BLZT_YB))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            resutlMap.put("fazzsl", fazzsl);
            resutlMap.put("xcjcsl", xcjcsl);

            return "1";
        }, executor);

        CompletableFuture<String> future3 = CompletableFuture.supplyAsync(() -> {

            // 综合评定数量
            long zhpdsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(SpcyFlowConstant.HJMC_ZHPD) && !f.getFblzt().equals(SpcyConstant.BLZT_YB))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            // 已移送数量
            long ysqrsl = jobList.stream()
                    .filter(f -> f.getFhjmc().equals(SpcyFlowConstant.HJMC_YSQR) && f.getFblzt().equals(SpcyConstant.BLZT_YB))
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            resutlMap.put("zhpdsl", zhpdsl);
            resutlMap.put("ysqrsl", ysqrsl);

            return "1";
        }, executor);


        try {
            CompletableFuture.allOf(future1, future2, future3).get();
        } catch (InterruptedException e) {
            log.error("[InterruptedException]获取本科室-各环节任务量: {}",e.getMessage());
        } catch (ExecutionException e) {
            log.error("[ExecutionException]获取本科室-各环节任务量: {}",e.getMessage());
        }

        return resutlMap;
    }

    /**
     * 查询我今年的任务量
     */
    public List<Map> getNowYearSpcyRwlInStat(String userid, boolean isHalfYear, String year){

        if (StringUtils.isBlank(year)){
            year = DateConversionUtils.DateToYear(new Date());
        }else {
            isHalfYear = false;
        }

        List<SpcyJobVo> jobList = spcyFlowMapper.selectMySpcyRwlList(userid, SpcyFlowConstant.LCMC_LIKE_SPCYLC, null, null,null, year, null);

        return countJobsPerMonthInYear(jobList, Integer.valueOf(year), isHalfYear, userid);
    }

    /** 用于计算列表中2024年每个月的SpcySqsxJob数量 */
    private static List<Map> countJobsPerMonthInYear(List<SpcyJobVo> jobList, int year, boolean isHalfYear, String userid) {
        List<Map> resultList = new ArrayList<>();

        Calendar calendar = new GregorianCalendar(year, Calendar.JANUARY, 1);
        calendar.set(Calendar.HOUR_OF_DAY, 0);
        calendar.set(Calendar.MINUTE, 0);
        calendar.set(Calendar.SECOND, 0);
        calendar.set(Calendar.MILLISECOND, 0);

        /** 是否只获取半年的数据量 */
        int nowMonth = 20;
        if (isHalfYear){
            nowMonth = Integer.valueOf(DateConversionUtils.DateToIntegerMonth2(new Date()));
        }

        for (int month = 0; month < 12; month++) {
            int finalMonth = month;

            if ((month+1) > nowMonth){
                break;
            }

            long dbsl = jobList.stream()
                    .filter(f -> !f.getFblzt().equals(SpcyConstant.BLZT_YB))
                    .filter(job -> job.getFfssj().after(calendar.getTime()) || job.getFfssj().equals(calendar.getTime()))
                    .filter(job -> {
                        Calendar jobCalendar = Calendar.getInstance();
                        jobCalendar.setTime(job.getFfssj());
                        return jobCalendar.get(Calendar.MONTH) <= finalMonth;
                    })
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            long ybsl = jobList.stream()
                    .filter(f -> f.getFblzt().equals(SpcyConstant.BLZT_YB)
                            && StringUtils.isNotBlank(f.getFblrid())
                            && f.getFblrid().equals(userid))
                    .filter(job -> job.getFfssj().after(calendar.getTime()) || job.getFfssj().equals(calendar.getTime()))
                    .filter(job -> {
                        Calendar jobCalendar = Calendar.getInstance();
                        jobCalendar.setTime(job.getFfssj());
                        return jobCalendar.get(Calendar.MONTH) <= finalMonth;
                    })
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();

            long zsl = dbsl + ybsl;
            /*long zsl = jobList.stream()
                    .filter(job -> job.getFfssj().after(calendar.getTime()) || job.getFfssj().equals(calendar.getTime()))
                    .filter(job -> {
                        Calendar jobCalendar = Calendar.getInstance();
                        jobCalendar.setTime(job.getFfssj());
                        return jobCalendar.get(Calendar.MONTH) <= finalMonth;
                    })
                    .collect(
                            Collectors.collectingAndThen(
                                    Collectors.toCollection(
                                            () -> new TreeSet<>(
                                                    Comparator.comparing(o -> o.getFpid())
                                            )
                                    ), ArrayList<SpcyJobVo>::new
                            )
                    )
                    .size();*/

//            jobCountPerMonth.put(month + 1, count); // Calendar的月份是从0开始的，所以需要+1

            Map dataMap = new HashMap();
            dataMap.put("index", month+1+"月");

            Map resultMap = new HashMap();
            resultMap.put("dbsl", dbsl);
            resultMap.put("ybsl", ybsl);
            resultMap.put("zsl", zsl);

            dataMap.put("data", resultMap);
            resultList.add(dataMap);

            // 设置下一个月的第一天
            calendar.add(Calendar.MONTH, 1);
            calendar.set(Calendar.DAY_OF_MONTH, 1);
        }

        return resultList;
    }

    /** 获取经办人-我的一个月任务量-旧方法 */
    public List<Map> countJobsPerWeekInMonthsMainOld(String userid) {

        String month = DateConversionUtils.DateToMonth(new Date());
        List<SpcyJobVo> jobList = spcyFlowMapper.selectMySpcyRwlList(userid, SpcyFlowConstant.LCMC_LIKE_SPCYLC, null, null, null,null, month);

        List<WeekMapVo> mapList = countJobsPerWeekInMonthsOld(jobList);

        List<Map> resultMapList = new ArrayList<>();
        for (int i = 0; i < 5; i++){

            int dbsl = 0;
            int ybsl = 0;
            int zsl = 0;

            int index = i+1;

            if (mapList.size()>i) {

                int week = mapList.get(i).getWeek();
                index = week;

                List<WeekMapVo> collect1 = mapList.stream().filter(f -> f.getWeek() == week).collect(Collectors.toList());
                if (CollectionUtil.isNotEmpty(collect1)) {
                    zsl = collect1.get(0).getZsl();
                    dbsl = collect1.get(0).getDbsl();
                    ybsl = collect1.get(0).getYbsl();
                }
            }else {
                break;
            }


            Map dataMap = new HashMap();
            if (mapList.size() == 0){
                index = i+1;
            }
            dataMap.put("index", "第"+index+"周");

            Map resultMap = new HashMap();
            resultMap.put("dbsl", dbsl);
            resultMap.put("ybsl", ybsl);
            resultMap.put("zsl", zsl);

            dataMap.put("data", resultMap);
            resultMapList.add(dataMap);
        }

        return resultMapList;
    }

    /** 获取经办人-我的一个月任务量-新方法 */
    public List<Map> countJobsPerWeekInMonthsMainNew(String userid){
        String yearMonth = DateConversionUtils.DateToMonth(new Date());
        int nowYear = Integer.valueOf(DateConversionUtils.DateToYear(new Date())); // 年份
        int nowMonth = Integer.valueOf(DateConversionUtils.DateToIntegerMonth2(new Date())); // 月份


        List<SpcyJobVo> jobList = spcyFlowMapper.selectMySpcyRwlList(userid, SpcyFlowConstant.LCMC_LIKE_SPCYLC, null, null, null,null, yearMonth);

        List<Map> resultList = new ArrayList<>();

        Map<Integer, Map<String, AtomicLong>> weeklyCounts = countJobsPerWeekInMonthsNew(jobList, nowYear, nowMonth);

        weeklyCounts.forEach((week, statusCounts) -> {

            Map dataMap = new HashMap();
            dataMap.put("index", "第"+week+"周");

            Map resultMap = new HashMap();
            resultMap.put("dbsl", (statusCounts.get(SpcyConstant.BLZT_DB).get() + statusCounts.get(SpcyConstant.BLZT_TH).get()));
            resultMap.put("ybsl", statusCounts.get(SpcyConstant.BLZT_YB).get());
            resultMap.put("zsl", statusCounts.get("总量").get());

            dataMap.put("data", resultMap);
            resultList.add(dataMap);
        });

        return resultList;
    }

    /** 计算每周的待办、已办和总量-旧方法 */
    private static List<WeekMapVo> countJobsPerWeekInMonthsOld(List<SpcyJobVo> jobList){
//        Map resultMap = new HashMap();
//        List<SpcyJobVo> jobList = new ArrayList<>(); // 初始化你的 jobList

        // 筛选 2024 年 3 月份的记录，并按 fpid 去重
        /*List<SpcyJobVo> filteredJobs = jobList.stream()
                .filter(job -> job.getLocalffssj().getYear() == 2024 && job.getLocalffssj().getMonthValue() == 3)
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(() -> new LinkedHashSet<>(Comparator.comparing(SpcyJobVo::getFpid))),
                        ArrayList::new
                ));*/

        AtomicLong dbsl = new AtomicLong();
        AtomicLong ybsl = new AtomicLong();
        AtomicLong zsl = new AtomicLong();

//        if (CollectionUtil.isNotEmpty(jobList)) {
            List<SpcyJobVo> filteredJobs = jobList.stream()
                    .collect(Collectors.collectingAndThen(
                            Collectors.toCollection(
                                    () -> new TreeSet<>(
                                            Comparator.comparing(o -> o.getFpid())
                                    )
                            ), ArrayList<SpcyJobVo>::new
                            )
                    );

            // 按周分组，并计算每组的已办、不等于已办的数量和总数
            Map<Integer, Map<String, Long>> weeklyCounts = filteredJobs.stream()
                    .collect(Collectors.groupingBy(
                            job -> getWeekOfYear(job.getLocalffssj()),
                            Collectors.groupingBy(
                                    SpcyJobVo::getFblzt,
                                    Collectors.counting()
                            )
                    ));

            // 计算总数
            Map<Integer, Long> weeklyTotals = weeklyCounts.entrySet().stream()
                    .collect(Collectors.toMap(
                            Map.Entry::getKey,
                            entry -> entry.getValue().values().stream().mapToLong(Long::longValue).sum()
                    ));

            List<WeekMapVo> dataList = new ArrayList<>();
            // 输出结果
            weeklyCounts.forEach((week, statusCounts) -> {
                /*Map data = new HashMap();
                data.put("week", week);*/

//                System.out.println("Week " + week + ":");
                statusCounts.forEach((status, count) -> {
                    if (SpcyConstant.BLZT_YB.equals(status)) {
//                    System.out.println("  已办: " + count);
                        dbsl.set(count);
                    } else {
//                    System.out.println("  不等于已办: " + count);

                        ybsl.set(count);
                    }
                });
//                System.out.println("  总数: " + weeklyTotals.get(week));
                zsl.set(weeklyTotals.get(week));

                /*data.put("dbsl", dbsl);
                data.put("ybsl", ybsl);
                data.put("zsl", zsl);*/

                dataList.add(new WeekMapVo(week, dbsl.intValue(), ybsl.intValue(), zsl.intValue()));
            });
//        }

        /*resultMap.put("dbsl", dbsl);
        resultMap.put("ybsl", ybsl);
        resultMap.put("zsl", zsl);*/
        return dataList;
    }

    /** 计算每周的待办、已办和总量-新方法 */
    private Map<Integer, Map<String, AtomicLong>> countJobsPerWeekInMonthsNew(List<SpcyJobVo> jobList, int nowYear, int nowMonth){
        List<SpcyJobVo> filteredJobs = jobList.stream()
                .collect(Collectors.collectingAndThen(
                        Collectors.toCollection(
                                () -> new TreeSet<>(Comparator.comparing(SpcyJobVo::getFpid))
                        ),
                        ArrayList::new
                ));

        // 获取 2024 年 3 月份的第一天和最后一天
        LocalDate firstDayOfMonth = LocalDate.of(nowYear, nowMonth, 1);
        LocalDate lastDayOfMonth = firstDayOfMonth.with(TemporalAdjusters.lastDayOfMonth());

        // 计算 3 月份的总周数
        int weeksInMonth = (int) ((lastDayOfMonth.get(ChronoField.ALIGNED_WEEK_OF_MONTH)
                - firstDayOfMonth.get(ChronoField.ALIGNED_WEEK_OF_MONTH)) + 1);

        // 初始化每周的待办、已办和总量为 0
        Map<Integer, Map<String, AtomicLong>> weeklyCounts = new HashMap<>();
        for (int i = 1; i <= weeksInMonth; i++) {
            weeklyCounts.put(i, new HashMap<>());
            weeklyCounts.get(i).put(SpcyConstant.BLZT_DB, new AtomicLong(0));
            weeklyCounts.get(i).put(SpcyConstant.BLZT_TH, new AtomicLong(0));
            weeklyCounts.get(i).put(SpcyConstant.BLZT_YB, new AtomicLong(0));
            weeklyCounts.get(i).put("总量", new AtomicLong(0));
        }

        // 划分每周的待办数量、已办数量和总量
        filteredJobs.forEach(job -> {
            // 获取该日期所在周数
            int weekOfMonth = job.getLocalffssj().get(ChronoField.ALIGNED_WEEK_OF_MONTH);

            // 增加总量
            weeklyCounts.get(weekOfMonth).get("总量").incrementAndGet();

            // 根据业务状态增加待办或已办数量
            if (SpcyConstant.BLZT_DB.equals(job.getFblzt())) {
                weeklyCounts.get(weekOfMonth).get(SpcyConstant.BLZT_DB).incrementAndGet();

            } else if (SpcyConstant.BLZT_YB.equals(job.getFblzt())) {
                weeklyCounts.get(weekOfMonth).get(SpcyConstant.BLZT_YB).incrementAndGet();

            } else if (SpcyConstant.BLZT_TH.equals(job.getFblzt())) {
                weeklyCounts.get(weekOfMonth).get(SpcyConstant.BLZT_TH).incrementAndGet();
            }
        });

        // 输出结果
        /*weeklyCounts.forEach((week, statusCounts) -> {
            System.out.println("Week " + week + ":");
            System.out.println("  待办: " + statusCounts.get("待办").get());
            System.out.println("  已办: " + statusCounts.get("已办").get());
            System.out.println("  总量: " + statusCounts.get("总量").get());
        });*/

        return weeklyCounts;
    }

    // 获取给定日期所在的周数（这里假设星期日为一周的开始）
    private static int getWeekOfYear(LocalDate date) {
        WeekFields weekFields = WeekFields.of(Locale.getDefault());
        return date.get(weekFields.weekOfWeekBasedYear());
    }

    /**
     * 1.专职人员派检率（中心人员参见到检查的次数/每月的检查次数）：百分比
     * --每月的检查次数：包含每年每月，现场检查次数
     * --中心人员参见到检查的次数：现场检查选派人员中存在中心人员
     * --
     * --（1）按照科室来统计
     * --（2）中心领导和财务看全部（红斌提供人员财务岗位和中心领导）
     * --（3）分管领导看分管科室。
     * --（4）科室看科室自己
     */
    public List<Map> zzRypjl(String userid, String year){
        if (StringUtils.isBlank(userid)){
            userid = GetCurrentUserUtils.getCurrentUserId();
        }

        if (StringUtils.isBlank(year)){
            year = DateConversionUtils.DateToYear(new Date());
        }

        // 月份
        /*List<String> monthList = CollectionUtil.newArrayList(
                "01", "02", "03", "04", "05", "06", "07", "08", "09", "10", "11", "12"
        );*/
        List<String> monthList = CollectionUtil.newArrayList(
                "1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"
        );

        // 科室事项编码
        List<String> ksCodeList = new ArrayList<>();

        // 验证是否为中心领导/财务人员
        List<String> zxldOrCwUserList = ycSysUserMapper.findZxldOrCwUserList(userid, SpcyConstant.GW_NAME_ZXLD, SpcyConstant.GW_NAME_CWRY);
        if (CollectionUtil.isEmpty(zxldOrCwUserList)){
            List<String> deptNamesList = new ArrayList<>();
            // 查询分管领导的部门ids
            List<String> fgldDeptIdList = ycSysUserMapper.findFgldDeptIdList(userid);
            if (CollectionUtil.isEmpty(fgldDeptIdList)){
                // 查询用户主部门id
                deptNamesList.addAll(ycSysUserMapper.findUserMajorDeptId(userid));
            }else {
                deptNamesList = ycSysUserMapper.findDeptNameListByDeptIds(fgldDeptIdList);
            }


            /** 科室名称转编码 */
            List<String> bzKsCodeList = CollectionUtil.newArrayList(
                    SpcyConstant.YWFL_CODE_YPZC,
                    SpcyConstant.YWFL_CODE_YPSC,
                    SpcyConstant.YWFL_CODE_YPJY,
                    SpcyConstant.YWFL_CODE_YLQX,
                    SpcyConstant.YWFL_CODE_HZP
            );
            for (String deptName : deptNamesList){
                String ywflByDeptName = SpcyConstant.getYwflByDeptName(deptName);
                if (bzKsCodeList.contains(ywflByDeptName)){
                    ksCodeList.add(ywflByDeptName);
                }
            }

        }else {
            ksCodeList = CollectionUtil.newArrayList(
                    SpcyConstant.YWFL_CODE_YPZC,
                    SpcyConstant.YWFL_CODE_YPSC,
                    SpcyConstant.YWFL_CODE_YPJY,
                    SpcyConstant.YWFL_CODE_YLQX,
                    SpcyConstant.YWFL_CODE_HZP
            );
        }

        List<Map> resultMap = new ArrayList<>();

        for (String code : ksCodeList){

            List<SpcySqsxBasic> yearSxList = spcyFlowMapper.selectYbxcjcSxList(code, year, null);
            List<SpcySqsxBasic> yearZxSxList = spcyFlowMapper.selectYbxcjcSxInZxcyList(code, year, null);

            List<Map> monthDataList = new ArrayList<>();
            for (String month : monthList) {

                int nowMonth = Integer.valueOf(month);

                // 查询已经办理现场检查的件
                int totalSize = yearSxList.stream().filter(f->{
                    LocalDate localDate = f.getFslsj().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                    // 使用YearMonth来比较年份和月份
                    YearMonth yearMonth = YearMonth.of(localDate.getYear(), localDate.getMonthValue());
                    return yearMonth.getMonthValue() == nowMonth;
                }).collect(Collectors.toList()).size();

                // 查询存在中心人员参与的检查件
                int zxcySize = yearZxSxList.stream().filter(f->{
                    LocalDate localDate = f.getFslsj().toInstant().atZone(ZoneId.systemDefault()).toLocalDate();

                    // 使用YearMonth来比较年份和月份
                    YearMonth yearMonth = YearMonth.of(localDate.getYear(), localDate.getMonthValue());
                    return yearMonth.getMonthValue() == nowMonth;
                }).collect(Collectors.toList()).size();

                Map monthDataMap = new HashMap();
//                monthDataMap.put("year", year);
//                monthDataMap.put("month", month);
                monthDataMap.put("yearMonth", (year+"年"+month+"月"));

                monthDataMap.put("total", totalSize);
                monthDataMap.put("zx", zxcySize);

                monthDataMap.put("data", StringPatternUtils.CalculatePpercentage(zxcySize, totalSize));
                monthDataMap.put("dataDw", "%");
                monthDataList.add(monthDataMap);
            }

            Map dataMap = new HashMap();
            dataMap.put("deptName", SpcyConstant.getOrgNameByCode(code));
            dataMap.put("list", monthDataList);
            resultMap.add(dataMap);
        }

        return resultMap;
    }


}
